<script lang="ts" setup>
import { reactive, ref } from "vue"
import { calcRatesApi, getBankssearchApi } from "@/api/calculator"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"

interface Props {
  amount?: number
  maturityDate?: string
  bank?: string
}

interface Emits {
  (e: "query-result", result: any): void
}

const props = withDefaults(defineProps<Props>(), {
  amount: 0,
  maturityDate: "",
  bank: ""
})

const emit = defineEmits<Emits>()

const formRef = ref<FormInstance | null>(null)
const loading = ref<boolean>(false)
const visible = ref<boolean>(false)
const queryResult = ref<any>(null)

const formData = reactive({
  amount: 0,
  maturity_date: "",
  bank: ""
})

const formRules: FormRules = reactive({
  amount: [{ required: true, trigger: "blur", message: "请输入票面金额" }],
  maturity_date: [{ required: true, trigger: "blur", message: "请选择到期日" }],
  bank: [{ required: true, trigger: "blur", message: "请选择承兑行" }]
})

// 银行搜索相关
const queryBankAsync = (queryString: string, cb: (suggestions: any[]) => void) => {
  if (queryString) {
    getBankssearchApi({ bank_name: queryString })
      .then((res: any) => {
        const suggestions = res.data.data.map((bank: any) => ({
          value: bank.bank_name,
          id: bank.bank_id,
          ...bank
        }))
        cb(suggestions)
      })
      .catch(() => {
        cb([])
      })
  } else {
    cb([])
  }
}

const handleBankSelect = (item: any) => {
  formData.bank = item.value
}

// 重置表单
const resetForm = () => {
  formData.amount = 0
  formData.maturity_date = ""
  formData.bank = ""
  queryResult.value = null
  formRef.value?.resetFields()
}

// 打开查询对话框
const openQuery = (data?: { amount?: number; maturity_date?: string; bank?: string }) => {
  if (data) {
    formData.amount = data.amount || props.amount
    formData.maturity_date = data.maturity_date || props.maturityDate
    formData.bank = data.bank || props.bank
  } else {
    formData.amount = props.amount
    formData.maturity_date = props.maturityDate
    formData.bank = props.bank
  }
  queryResult.value = null
  visible.value = true
}

// 执行查询
const handleQuery = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true
      calcRatesApi({
        amount: formData.amount,
        maturity_date: formData.maturity_date,
        bank: formData.bank
      })
        .then((res: any) => {
          queryResult.value = res.data
          emit("query-result", res.data)
          ElMessage.success("查询成功")
        })
        .catch((error) => {
          ElMessage.error("查询失败：" + (error.message || "未知错误"))
          queryResult.value = null
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  resetForm()
}

// 暴露方法给父组件调用
defineExpose({
  openQuery
})
</script>

<template>
  <el-dialog v-model="visible" title="利率查询" width="600px" @close="handleClose">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="left"
      v-loading="loading"
    >
      <el-form-item prop="amount" label="票面金额">
        <el-input-number
          v-model="formData.amount"
          :min="0"
          :precision="2"
          placeholder="请输入票面金额"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item prop="maturity_date" label="到期日">
        <el-date-picker
          v-model="formData.maturity_date"
          type="date"
          placeholder="请选择到期日"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item prop="bank" label="承兑行">
        <el-autocomplete
          v-model="formData.bank"
          :fetch-suggestions="queryBankAsync"
          placeholder="请输入搜索承兑行"
          @select="handleBankSelect"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <!-- 查询结果展示 -->
    <div v-if="queryResult" class="query-result">
      <el-divider content-position="left">查询结果</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="票面金额">¥{{ queryResult.amount }}</el-descriptions-item>
        <el-descriptions-item label="到期日">{{ queryResult.maturity_date }}</el-descriptions-item>
        <el-descriptions-item label="承兑行">{{ queryResult.bank }}</el-descriptions-item>
        <el-descriptions-item label="利率值">
          <span v-if="queryResult.rate_mode === 'FIXED'">{{ queryResult.rate }}%</span>
          <span v-else-if="queryResult.rate_mode === 'FLOAT'">{{ queryResult.rate }}%</span>
          <span v-else-if="queryResult.rate_mode === 'FIXED_AMOUNT'">¥{{ queryResult.rate }}</span>
          <span v-else>{{ queryResult.rate }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="贴现费">¥{{ queryResult.interest }}</el-descriptions-item>
        <el-descriptions-item label="贴现金额">¥{{ queryResult.discount_amount }}</el-descriptions-item>
      </el-descriptions>
    </div>

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="primary" @click="handleQuery" :loading="loading">查询利率</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.query-result {
  margin-top: 20px;
}
</style>
